package com.zw.admin.server.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zw.admin.server.mapper.CommentMapper;
import com.zw.admin.server.model.Comment;
import com.zw.admin.server.service.CommentService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
@Slf4j
public class CommentController {

    @Autowired
    private CommentService commentService;

    @ApiOperation(value = "更新评论")
    @PostMapping(value = "/update", produces = "application/json;charset=UTF-8")
    public String update(@RequestBody List<Comment> commentList) throws Exception {
        for (Comment comment : commentList) {
            commentService.updateById(comment);
        }
        return "success";
    }


    @ApiOperation(value = "新增评论")
    @PostMapping(value = "/insert", produces = "application/json;charset=UTF-8")
    public String insert(@RequestBody Comment comment) throws Exception {
        log.info("插入一条评论: " + comment.toString());
        if (comment.getContent() != null && !comment.getContent().equals("")&& !comment.getUserCode().equals("")) {
            comment.setStatus(0);
            commentService.save(comment);
            return "success";
        } else {
            return "插入失败，评论内容和用户信息不能为空";
        }

    }

    @ApiOperation(value = "获取所有评论")
    @GetMapping("/{status}/{pageNum}")
    public String getComment(@PathVariable("status") String status,
                             @PathVariable(value = "pageNum") int pageNum) throws Exception {
        /*
        *0-未审核-unreview
		1-审核通过-pass
		2-审核不通过-fail
        * */
        int code = 0;
        if ("pass".equals(status)) {
            code = 1;
        }
        if ("fail".equals(status)) {
            code = 2;
        }
        QueryWrapper<Comment> commentQW = new QueryWrapper<Comment>();
        commentQW.eq("status", code);
        commentQW.orderByDesc("insert_time");

        Page<Comment> page = new Page<>(pageNum, 10);
        return JSON.toJSONString(commentService.page(page, commentQW));
    }

    @ApiOperation(value = "获取所有评论")
    @GetMapping("/{status}")
    public String getAllComment(@PathVariable("status") String status) throws Exception {
        /*
        *0-未审核-unreview
		1-审核通过-pass
		2-审核不通过-fail
        * */
        int code = 0;
        if ("pass".equals(status)) {
            code = 1;
        }
        if ("fail".equals(status)) {
            code = 2;
        }
        QueryWrapper<Comment> commentQW = new QueryWrapper<Comment>();
        commentQW.eq("status", code);
        commentQW.orderByDesc("insert_time");

        return JSON.toJSONString(commentService.list( commentQW));
    }

}
